#!/usr/bin/env python3
import argparse
import requests
import cv2
import base64
import os
import numpy as np

# python http_client.py http://0.0.0.0:8000 --image car.png

def main():
    parser = argparse.ArgumentParser(description='HTTP image client for brpc server')
    parser.add_argument('url', help='Server URL, e.g. "http://0.0.0.0:8000"')
    parser.add_argument('--image', required=True, help='Path to the image file')
    parser.add_argument('--timeout', type=float, default=2.0, help='Request timeout in seconds')
    args = parser.parse_args()

    # 构建完整URL
    url = f"{args.url}/HttpService/Echo"

    try:
        # 读取图片
        img = cv2.imread(args.image)
        if img is None:
            print(f"Error: Cannot read image file: {args.image}")
            return 1

        # 将图片编码为PNG格式以保持无损压缩
        _, img_encoded = cv2.imencode('.png', img)

        # 将图片转换为base64字符串
        img_base64 = base64.b64encode(img_encoded.tobytes()).decode('utf-8')

        # 获取原始文件名
        image_name = os.path.basename(args.image)

        # 构建JSON数据
        data = {
            "image_data": img_base64,
            "image_name": image_name
        }

        # 发送POST请求
        response = requests.post(
            url,
            json=data,
            headers={'Content-Type': 'application/json'},
            timeout=args.timeout,
            proxies={'http': None, 'https': None}  # 禁用代理
        )

        # 检查响应状态
        response.raise_for_status()

        # 解析响应JSON
        resp_data = response.json()
        print(f"Server response: {resp_data['message']}")

        if resp_data['success'] and 'image_data' in resp_data:
            # 解码返回的图像
            img_data = base64.b64decode(resp_data['image_data'])
            nparr = np.frombuffer(img_data, np.uint8)
            img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

            if img is not None:
                # 显示图像
                cv2.imshow('Processed Image', img)
                cv2.waitKey(0)

                # 打印检测到的矩形信息
                print("\nDetected rectangles:")
                print(resp_data['img_rect'])
                for i, rect in enumerate(resp_data['rect']):
                    print(f"Rectangle {i+1}: x={rect['x']}, y={rect['y']}, "
                          f"w={rect['w']}, h={rect['h']}")
            else:
                print("Error: Could not decode received image")

    except Exception as e:
        print(f"Error: {e}")
        return 1

    return 0

if __name__ == '__main__':
    exit(main())